package com.nikitova.craps3d.model 
{
	import com.carlcalderon.arthropod.Debug;
	import com.nikitova.craps3d.constants.Notifications;
	import com.nikitova.craps3d.model.vo.GameConfigVO;
	import com.nikitova.craps3d.model.vo.PhysicsVO;
	import com.nikitova.utils.data.PathUtils;

	import org.puremvc.as3.multicore.utilities.startupmanager.interfaces.IStartupProxy;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class GameConfigProxy extends EntityProxy implements IStartupProxy 	{		public static const NAME : String = 'GameConfigProxy';		public static const SRNAME : String = 'GameConfigSRProxy';
		private var __gameConfigXMLPath : String;

		public function GameConfigProxy()
		{			super(NAME);		}
		//**PUBLIC METHODS**//
		public function load() : void
		{
			var xmlurl : String = PathUtils.formatURI(__gameConfigXMLPath, { v: Math.random().toString() });
			var request : URLRequest = new URLRequest(xmlurl);
			var loader : URLLoader = new URLLoader();
			
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			loader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
			
			loader.load(request);
		}

		//**GETTER/SETTER**//
		public function get gravity() : Number
		{
			return gameConfigVO.physics.gravity;
		}

		public function get showAxis() : Boolean
		{
			return gameConfigVO.showAxis;
		}

		public function set gameConfigXMLPath(value : String) : void
		{
			__gameConfigXMLPath = value;
		}

		//**PRIVATE METHODS**//		
		private function loaderCompleteHandler( event : Event ) : void 
		{
			var xml : XML;
			XML.ignoreWhitespace = true;
			try
			{
				xml = new XML(event.target.data);
			}
			catch (error : TypeError)
			{
				sendLoadedNotification(Notifications.CONFIG_LOAD_FAILED, NAME, SRNAME);
				return;
			}
			
			var vo : GameConfigVO = new GameConfigVO();
			
			var overallXML : XMLList = xml.overall;
			
			var physicsXML : XMLList = overallXML.physics;
			vo.physics = new PhysicsVO(physicsXML.gravity);
			vo.showAxis = (overallXML.showAxis == "false")? false:true;
			
			data = vo;
			
			sendNotification(Notifications.INIT_GAME_CONFIG);
			sendLoadedNotification(Notifications.GAME_CONFIG_LOADED, NAME, SRNAME);
		}

		private function errorHandler( event : IOErrorEvent ) : void 
		{
			sendLoadedNotification(Notifications.GAME_CONFIG_LOAD_FAILED, NAME, SRNAME);
		}

		private function get gameConfigVO() : GameConfigVO
		{
			return data as GameConfigVO;
		}
	}}